package io.chance.receiverlei.db.model;

import io.chance.receiverlei.datapacket.ModbusCRCUnit;
import io.chance.receiverlei.main.AppStart;
import lrq.common.MyLog;
import org.apache.log4j.Logger;

import java.util.Date;

public class RequestModel {
    public static final String[] FUNC_HEXs = {
        "010401018049",
        "01040102C048",
        "010401030188",
        "01040104404A",
        "01040105818A",
        "01040106C18B",
        "01040107004B",
//        "01040408010000A824",
        "010E002460"
    };
    public static final String FUNC_HEX_NEW = "01030106000BE5F0";

    static Logger log;

    /**
     * 对应的是modbus从站编号，也就是设备编号,十进制字符
     */
    private String mn;

    /**
     * 查询的起始地址，对应污染物的编号,十进制
     */
    private int startAddr;

    /**
     * 询问数据长度
     */
    private int dataLength;

    /**
     * 和查询的起始地址对应，翻译成污染物名称
     */
    private String attrName;

    /**
     * 请求的时间
     */
    private Date requestDate;


    public String getMn() {
        return mn;
    }

    public void setMn(String mn) {
        this.mn = mn;
    }

    public int getStartAddr() {
        return startAddr;
    }

    public void setStartAddr(int startAddr) {
        this.startAddr = startAddr;
    }

    public String getAttrName() {
        return attrName;
    }

    public void setAttrName(String attrName) {
        this.attrName = attrName;
    }

    public Date getRequestDate() {
        return requestDate;
    }

    public void setRequestDate(Date requestDate) {
        this.requestDate = requestDate;
    }

    public int getDataLength() {
        return dataLength;
    }

    public void setDataLength(int dataLength) {
        this.dataLength = dataLength;
    }

    /**
     * 把要发送的数据转成byte[]
     * gislin
     * 2016年4月14日
     *
     * @return
     */
    public byte[] getSendByte() {

        if (log == null) {
            log = MyLog.getLogger(AppStart.logName);
        }

        int mnInt = Integer.parseInt(mn);
        int functionCode = 3;
        int startAddress01 = (0x000000FF & (startAddr >> 8));
        int startAddress02 = (0x000000FF & startAddr); //如果起始位是255以上，这里就会有问题
        int dataLength01 = 0;
        int dataLength02 = dataLength; //如果超过255，这里就会有问题

        byte[] data = {
            (byte) mnInt,
            (byte) functionCode,
            (byte) startAddress01,
            (byte) startAddress02,
            (byte) dataLength01,
            (byte) dataLength02,
            0,
            0
        };

        //log.info("询问报文："+mnInt + " " + functionCode + " " + startAddress01 + " " + startAddress02 +" " + dataLength01+ " "+dataLength02 );

        byte[] crcByte = ModbusCRCUnit.getCRCByte(data);
        data[6] = crcByte[0];
        data[7] = crcByte[1];
        return data;
    }

}